package com.atguigu.juc.cf;

import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * @author yanglin
 * @create 2023-12-28 10:14 星期四
 * description:
 */

//future结合线程池
public class FutureThreadPoolDemo {
    
    
    @Test
    public void testFutureThreadPool2() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        //线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        //三个任务  开启多个异步线程执行
        FutureTask<String> f1 = new FutureTask<String>(() -> {
            //task1
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task1 over";
        });
        threadPool.submit(f1);

        FutureTask<String> f2 = new FutureTask<String>(() -> {
            //task2
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "task2 over";
        });

        threadPool.submit(f2);

        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String s1 = f1.get();
        String s2 = f2.get();
        //释放线程池
        threadPool.shutdown();
        
        long endTime = System.currentTimeMillis();
        System.out.println("耗时：" + (endTime - startTime) + " 毫秒");
        
    }
    
    @Test
    public void testFutureThreadPool(){
        long startTime = System.currentTimeMillis();
        //三个任务全部由main线程执行
        //task1
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //task2
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //task3
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("耗时：" + (endTime - startTime) + " 毫秒");
    }
    
}
